package com.wjw.juc;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

//lock优化synchronized
class Ticket{
    private int ticket = 500;

    private static final Lock lock = new ReentrantLock();

    public void saleTicket(){

        lock.lock();
        try {
            if (ticket > 0){
                System.out.println(Thread.currentThread().getName() +",卖出第" + ticket-- +"张票，还剩" + ticket + "张票;");
            }
        } finally {
            lock.unlock();
        }
    }
}
public class LockDemo {
    public static void main(String[] args) {

        final Ticket ticket = new Ticket();
        new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i< 1000;i++){
                    ticket.saleTicket();
                }
            }
        }, "A").start();
        new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i< 1000;i++){
                    ticket.saleTicket();
                }

            }
        },"B").start();
    }
}
